package com.lzx.iteam.net;

import android.os.Message;
import android.util.Log;
import com.lzx.iteam.bean.ApprovalGroupData;
import com.lzx.iteam.bean.AtDateBean;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by xuepengju on 14-3-20.
 */
public class GetApprovalCalendarMsg extends CcMsgStructure {

    private Message mmCallback;

    public GetApprovalCalendarMsg(Message callback){
        mmCallback = callback;
    }

    @Override
    public void onReceive(JSONObject data) {

        HashMap<String,Object> map = new HashMap<>();
        try {
            JSONObject jsonObject = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
            JSONObject attendance_form = jsonObject.getJSONObject("attendance_form");
            map.put("form_type",attendance_form.getInt("form_type"));
            map.put("date",attendance_form.getString("date"));

            JSONArray jsonArray = jsonObject.getJSONArray("attendance_calendars");
//            ArrayList<AtDateBean> beans = new ArrayList<>();
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                AtDateBean bean = new AtDateBean();
                bean.set_id(obj.getString("_id"));
                bean.setDay(obj.getInt("day"));
                bean.setStatus(obj.getInt("status"));
                map.put(obj.getString("day"),bean);
            }
        } catch (JSONException e) {
            Log.e("My_JSONException",e.toString());
        }
        if (mmCallback != null)
        {
            mmCallback.obj = map;
            mmCallback.arg1 = 0;
            mmCallback.sendToTarget();
            return;
        }
    }

    @Override
    public void onError(int error, Object ret) {
        String errorMsg = null;
        if (ret != null) {
            JSONObject jData = null;
            try {
                jData = new JSONObject(ret.toString());
                errorMsg = jData.getString("msg");
            } catch (JSONException e) {
                errorMsg = "服务端数据解析失败!";
                e.printStackTrace();
            }

        }
        if(mmCallback != null){
            mmCallback.arg1 = error;
            if(!StringUtil.isEmpty(errorMsg)){
                mmCallback.obj = errorMsg;
            }else{
                mmCallback.obj = Constants.NETWORK_WRROR;
            }
            mmCallback.sendToTarget();
        }
    }
}
